<template>
  <el-dialog v-model="visible" title="文档清单" append-to-body width="70%">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template #menu="{ size, row, index }">
        <el-button @click="fileClick(row)" text type="primary" icon="el-icon-view">
          切片文档
        </el-button>
      </template>
    </avue-crud>
  </el-dialog>
  <el-drawer
    v-model="drawer"
    :title="drawerTitle"
    size="800px"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <el-collapse
      v-model="activeNames"
      @change="handleChange"
      v-loading="loading"
      v-if="activeNames"
    >
      <div v-for="(item, index) in fileBlockdata">
        <div v-if="isTextTruncated[index]" class="title">
          {{ item.content }}
        </div>
        <el-collapse-item :name="index" v-else>
          <template #title>
            <div class="collapseStyle" ref="textElements" :id="index">
              {{ item.content }}
            </div>
          </template>
        </el-collapse-item>
      </div>
    </el-collapse>
  </el-drawer>
</template>

<script>
import { getFileList, remove, getFileBlockData } from '@/api/knowledge/datasetList';
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      isTextTruncated: [],
      activeNames: [],
      activeArr: [],
      loading: false,
      fileBlockdata: [],
      drawerTitle: '',
      drawer: false,
      datasetId: '',
      visible: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        delBtn: true,
        editBtn: false,
        addBtn: false,
        // grid: true,
        selection: false,
        dialogClickModal: false,
        addBtnText: '新增知识库',
        column: [
          {
            label: '文件名称',
            prop: 'name',
            span: 24,
            search: true,
            searchLabelWidth: 90,
            labelWidth: 120,
            rules: [
              {
                required: true,
                message: '请输入数据集名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '文档状态',
            prop: 'display_status',
            display: false,
          },
          {
            label: '创建时间',
            prop: 'created_at',
            display: false,
          },
          {
            label: '异常备注',
            prop: 'error',
            display: false,
          },
        ],
      },
      data: [],
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        // addBtn: this.validData(this.permission.datasource_add, false),
        // viewBtn: this.validData(this.permission.datasource_view, false),
        // delBtn: this.validData(this.permission.datasource_delete, false),
        // editBtn: this.validData(this.permission.datasource_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  // mounted() {
  //   this.checkTextOverflow();
  // },
  methods: {
    handleChange(val) {
      console.log(val, 'val');
      //不是最后一个收起
      // if (val && val.length > 0) {
      //点击收起
      if (this.activeArr.length > val.length) {
        this.activeArr.forEach((item, index) => {
          if (val.indexOf(item) === -1) {
            console.log(index, 'index');
            console.log(this.activeArr[index - 1], 'this.activeArr[index]');
            // this.activeArr[index]
            const id = this.activeArr[index];
            const demo1 = document.getElementById(id);
            demo1.classList.add('collapseStyle');
            demo1.classList.remove('text');
            return;
          }
        });
      } else {
        console.log(11111111111);
        //点击展开
        val.forEach(item => {
          const demo1 = document.getElementById(item);
          demo1.classList.remove('collapseStyle');
          demo1.classList.add('text');
        });
      }
      // } else {
      //   console.log(222222222222);
      //   //最后一个收起
      //   const demo1 = document.getElementById('0');
      //   demo1.classList.add('collapseStyle');
      //   demo1.classList.remove('text');
      // }

      this.activeArr = val;
    },
    checkTextOverflow() {
      if (this.$refs.textElements && this.$refs.textElements.length > 0) {
        this.isTextTruncated = this.$refs.textElements.map(el => {
          return el.scrollWidth <= el.clientWidth;
        });
      }
      // });
    },
    //打开前请求切片接口
    // getData(row) {
    //   console.log(row, 'row233');

    // },
    handleClose() {
      console.log(8888888);
      this.activeArr = [];
      this.activeNames = [];
      this.fileBlockdata = [];
      this.isTextTruncated = [];
    },
    fileClick(row) {
      // this.loading = true;
      // getFileBlockData(this.datasetId, row.id).then(
      //   res => {
      //     console.log(res, 'res');
      //     if (res && res.status == 200) {
      //       this.fileBlockdata = res.data.data;
      //       this.loading = false;
      //       this.$nextTick(() => {
      //         this.checkTextOverflow();
      //       });
      //     } else {
      //       this.fileBlockdata = [];
      //       this.loading = false;
      //     }
      //   },
      //   error => {
      //     this.fileBlockdata = [];
      //     this.loading = false;
      //   }
      // );
      // console.log(row, 'row');
      // this.drawer = true;
      // this.drawerTitle = row.name;
      // 每次打开时重新加载数据
      this.loading = true;
      this.drawer = true;
      this.drawerTitle = row.name;

      getFileBlockData(this.datasetId, row.id).then(
        res => {
          if (res && res.status === 200) {
            this.fileBlockdata = res.data.data;
          } else {
            this.fileBlockdata = [];
          }
          this.loading = false;
          this.$nextTick(() => {
            this.checkTextOverflow();
          });
        },
        error => {
          this.fileBlockdata = [];
          this.loading = false;
        }
      );
    },
    rowSave(row, done, loading) {
      add(row.name).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.datasetId, row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getFileList(
        this.datasetId,
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        console.log(res.data.data, 'res');
        const data = res.data;
        this.page.total = data.total;
        this.data = data.data;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>
<style scoped>
.title {
  color: #303113;
  font-size: 14px;
  height: 48px;
  line-height: 48px;
  border-bottom: 1px solid #ebeef5;
}

.collapseStyle {
  width: 730px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.text {
  text-align: left;
}
</style>